package com.major.sort.mergersorting;

public class MergeSort {

    public static void merge(int[] arr) {
        int[] temp = new int[arr.length];
        merge(arr, 0, arr.length - 1, temp);
    }

    // 分
    private static void merge(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            // 向左分
            merge(arr, left, mid, temp);
            // 向右分
            merge(arr, mid + 1, right, temp);
            // 合
            mergeSort(arr, left, mid, right, temp);
        }
    }

    // 合
    private static void mergeSort(int[] arr, int left, int mid, int right, int[] temp) {
        // temp的指针
        int i = 0;
        int r = mid + 1;
        int l = left;

        // 两边的填到temp
        while (l <= mid && r <= right) {
            if (arr[l] < arr[r]) {
                temp[i] = arr[l];
                i++;
                l++;
            } else {
                temp[i] = arr[r];
                r++;
                i++;
            }
        }
        // 剩余的填到temp
        while (l <= mid) {
            temp[i] = arr[l];
            l++;
            i++;
        }
        while (r <= right) {
            temp[i] = arr[r];
            r++;
            i++;
        }

        // temp 赋给 arr
        i = 0;
        int tempLeft = left;
        // 每次只拷贝当前长度的数组，而不是整个数组
        while (tempLeft <= right) {
            arr[tempLeft] = temp[i];
            tempLeft++;
            i++;
        }

    }

}
